﻿using System.IO;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Ultima.Xna.Data
{
    public class Hues
    {
        private static GraphicsDevice _graphicsDevice;
        private static Texture2D _texture;

        public static Texture2D Texture
        {
            get { return _texture; }
        }

        // Each hue is 32 pixels wide, so divided by 32 = 2 hues wide.
        public const int TextureWidth = 64; 
        public const int TextureHeight = 2024;

        public static void Inititlize(Game game)
        {
            if (_graphicsDevice != null)
            {
                _graphicsDevice.DeviceReset -= new System.EventHandler(OnGraphicsDeviceDeviceReset);
            }

            _graphicsDevice = game.GraphicsDevice;
            _graphicsDevice.DeviceReset += new System.EventHandler(OnGraphicsDeviceDeviceReset);

            CreateTexture(_graphicsDevice);
        }

        static void OnGraphicsDeviceDeviceReset(object sender, System.EventArgs e)
        {
            CreateTexture(_graphicsDevice);
        }

        private static void CreateTexture(GraphicsDevice graphicsDevice)
        {
            ushort[] data = new ushort[TextureWidth * TextureHeight];

            int currentHue = 0;

            using (BinaryReader reader = new BinaryReader(FileManager.GetFile("hues.mul")))
            {
                while (reader.BaseStream.Position < reader.BaseStream.Length)
                {
                    reader.ReadInt32(); //Header

                    for (int entry = 0; entry < 8; entry++ )
                    {
                        for (int i = 0; i < 32; i++)
                        {
                            data[currentHue * 32 + i] = (ushort)(reader.ReadUInt16() | 0x8000);
                        }

                        currentHue++;

                        reader.ReadInt16(); //table start
                        reader.ReadInt16(); //table end
                        reader.ReadBytes(20); //name
                    }
                }

                reader.Close();
            }

            _texture = new Texture2D(graphicsDevice, TextureWidth, TextureHeight, 1, TextureUsage.None, SurfaceFormat.Bgra5551);
            _texture.SetData<ushort>(data);
            ushort[] d = new ushort[TextureWidth * TextureHeight];
            _texture.GetData<ushort>(d);
        }
    }
}